package me.goldze.mvvmhabit.base;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.widget.LinearLayout;

import com.hjq.toast.ToastUtils;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.Map;

import me.goldze.mvvmhabit.BR;
import me.goldze.mvvmhabit.R;
import me.goldze.mvvmhabit.databinding.ActBaseWebViewBinding;
import me.goldze.mvvmhabit.lks.router.RouteHelper;
import me.goldze.mvvmhabit.utils.NoDoubleClickListener;
import me.goldze.mvvmhabit.utils.SPUtils;

public class ActBaseWebView extends BaseActivity<ActBaseWebViewBinding, BaseViewModel>   {
    private WebView webView;
    String url;
    String title;
    int type;
    int needLogin;//0 需要登录 1 不需要
    LinearLayout llContainer;

    public static void start(Context context, String url, String title, int type) {
        Intent starter = new Intent(context, ActBaseWebView.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        bundle.putString("title", title);
        bundle.putInt("type", type);
        starter.putExtras(bundle);
        context.startActivity(starter);
    }

    public static void startForResult(Activity context, String url, String title, int type) {
        Intent starter = new Intent(context, ActBaseWebView.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        bundle.putString("title", title);
        bundle.putInt("type", type);
        starter.putExtras(bundle);
        context.startActivityForResult(starter, 0);
    }

    private void downloadByBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && null != webView && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
//        llContainer.setVerticalGravity(View.GONE);
//        resetWebView();
        setResult(RESULT_OK);
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.setVisibility(View.GONE);
        }
        super.onDestroy();
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_base_web_view;
    }

    @Override
    public void initData() {
        Bundle extras = getIntent().getExtras();
        url = extras.getString("url");
        title = extras.getString("title");
        type = extras.getInt("type", 0);
        needLogin = extras.getInt("needLogin", 0);

        webView = new WebView(this);

        showDialog();
//        bridge=new NativeJsBridge();
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setTextSize(WebSettings.TextSize.LARGEST);
//支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);
//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件
//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setDomStorageEnabled(true);
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.clearCache(true);
        webView.addJavascriptInterface(this, "nativeMethod");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(0);
        }
        llContainer = (LinearLayout) findViewById(R.id.llContainer);
//        webView.addJavascriptInterface(this, "Android_Method");
        webView.setWebChromeClient(new WebChromeClient() {
            // For Android > 5.0
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                return true;
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return true;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
                sslErrorHandler.proceed();
                super.onReceivedSslError(webView, sslErrorHandler, sslError);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                if (webView.getUrl().equals(ActBaseWebView.this.url)) {
                    ActBaseWebView.this.webView.setVisibility(View.VISIBLE);
                }
                dismissDialog();
                if(needLogin==0&&TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.TOKEN))){
                    viewModel.startModuleActivity("user_ActLogin", null);
                    finish();
                }
                super.onPageFinished(webView, s);
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                super.doUpdateVisitedHistory(view, url, isReload);
//                if(url.equals(ActBaseWebView.this.url)){
//                    webView.clearHistory();
//                }
//                if(url.contains("base64")&&type==1){
//                    webView.clearHistory();
//                }
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                downloadByBrowser(url);
            }
        });
        if (!TextUtils.isEmpty(title)) {
            getTitleBar().setTitileString(title);
            getTitleBar().setBackListener(new NoDoubleClickListener() {
                @Override
                protected void onNoDoubleClick(View v) {
                    if (null != webView && webView.canGoBack()) {
                        webView.goBack();// 返回前一个页面
                    } else {
                        finish();
                    }
                }
            });
        }
        if (type == 1) {
            webView.clearHistory();
            webView.loadDataWithBaseURL(null, url, "text/html", "utf-8", null);
            webView.setVisibility(View.VISIBLE);
        } else {
//            CookieManager cookieManager = CookieManager.getInstance();
//            cookieManager.setAcceptCookie(true);
//            cookieManager.removeSessionCookie();// 移除
//            cookieManager.removeAllCookie();
//            cookieManager.setCookie(url, SPUtils.getInstance().getString(Constants.TOKEN));
//            CookieSyncManager.getInstance().sync();
            if (url.contains("?")) {
                url = url + "&webviewtoken=" + SPUtils.getInstance().getString(Constants.TOKEN);
            } else {
                url = url + "?webviewtoken=" + SPUtils.getInstance().getString(Constants.TOKEN);
            }
            Log.e("bruce", "initData: >>>>url>>>>>>>>" + url);
            webView.loadUrl(url);
        }
        ViewParent parent = webView.getParent();
        if (null != parent) {
            if (parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(webView);
            }
        }
        llContainer.addView(webView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
//        showLoading();
//        loadRewardVideo(Constants.AD_VIDEO);
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    private void resetWebView() {
        webView.setVisibility(View.GONE);
        webView.loadUrl("");
        webView.clearHistory();
    }

    @JavascriptInterface
    public void commodityDetail(String shopNo, String id) {
//        ToastUtils.show("commodityDetail>>>>>>>>>>>>>>>>>>>");
        Log.e("bruce", "commodityDetail: >>>>>shopNo:" + shopNo + ">>>>>>id:" + id);
        Bundle bundle = new Bundle();
        bundle.putString("shopNo", shopNo);
        bundle.putInt("id", Integer.parseInt(id));
        Intent intent = new Intent();
        intent.putExtra(RouteHelper.ROUTE_KEY, "main_ActCommodityDetails");
        intent.putExtras(bundle);

        startModuleActivity(intent, 10);
    }

    String params;

    @JavascriptInterface
    public void showAd(String params) {
        this.params = params;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                adShow();
            }
        });

    }

    @JavascriptInterface
    public void login() {
        viewModel.startModuleActivity("user_ActLogin", null);
        finish();
    }

}